/*
 * @Descripttion:
 * @version: v1.0
 * @Author: Zc
 * @Date: 2022/4/10 14:51
 * @LastEditors: Zc
 * @LastEditTime: 2022/4/10 14:51
 */
import { reactive } from 'vue'
import RouteConst from '../../router/routeConst'
import { assign3 } from '../utils/normalUtils'
import {
    clearPageCatch,
    clearSystemCatch,
    initSystemCatch,
    saveSystemCatch
} from './permission'
import {changeRoute} from "../../router";


// 系统状态
export const appState:any = reactive({
    // 顶层加载状态
    isLoading: false,
    embedMode: true,
    debugMode: false, // 纯本地测试模式 不做验证
    title: '',
    userInit: false,
    miniMenu: false,
    defaultRoute: RouteConst.HOME,
    // 当前登录用户
    currentUser: {
        userId: '',
        username: '大幅度发',
        nickname: '',
        img: '',
        email: '',
        depId: '',
        permissions: []
    },
    config: {
        sys: '',
        name: '',
        alias: '',
        code: 'xt_code',
        version: '1.0.0',
        largeFile: 52428800
    },
    baseUrl: (import.meta as any).env.VITE_APP_BASE_API !== null ? (import.meta as any).env.VITE_APP_BASE_API?.toString() : '',
    menu: []
})

/**
 * 系统初始化
 */
export const initApp = () => {
    const win: any = window
    assign3(appState.config, win.SYSTEMCONFIG || {})
    appState.version = appState.config.version || '1.0.0'
    // 重置下状态 不和以前逻辑掺和
    appState.userInit = false
    // 初始化缓存信息
    const catchInfo = initSystemCatch()
    // 如果有token衔接下原来的逻辑
    if (catchInfo) initUserLoginInfo(catchInfo, false)
}

/**
 * 是否是嵌入模式 temp?
 */
export function isEmbedMode() {
    return window.top !== window.self
}


/**
 * 初始化登录用户信息
 */
export const initLoginInfo = () => {
 }

/**
 * 显示系统最外层状态
 * @param value
 */
export function showAppLoading(value = true) {
    const loadingDom:any = document.getElementById('app-loader-wrapper')
    loadingDom.style.display = value ? 'flex' : 'none'
}

/**
 * 初始化用户基本信息 衔接下以前的配置 保证token可取 temp?
 */
export function initUserLoginInfo(userInfo:any, catchData = true) {
    appState.currentUser.username = userInfo.userName
    appState.currentUser.userId = userInfo.userId
    if (catchData)saveSystemCatch(userInfo)
    appState.userInit = true
}

/**
 * 退出系统
 */
export async function exitApp() {
    clearSystemCatch()
    initReloadSystem()
}

/**
 * 重新加载系统页面
 */
export const initReloadSystem = async (reload=true) => {
    clearPageCatch()
    await changeRoute(RouteConst.LOGIN)
    if(reload)window.location.reload()
}
